/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ctrl;

import model.BookingBackingBean;
import model.ViewFreeRoomsBackingBean;
import entities.Booking;
import hotel.jpa.Database;
import hotel.jpa.IRoomJpaCtrl;
import hotel.jpa.RoomJpaCtrl;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Viktor
 */
@ManagedBean(name = "bookingControllerBean")
public class BookingControllerBean {

    protected List<ViewFreeRoomsBackingBean> freeRooms = new ArrayList<ViewFreeRoomsBackingBean>();

    public List<ViewFreeRoomsBackingBean> getFreeRooms() {

        addFreeRooms();

        return freeRooms;
    }

    /**
     * Looks if the incoming "FromDate" from the customer match 
     * with the bookings in the database. Only adds aviavable rooms  
     * in the list to view the customer.  
     *
     */
    public void addFreeRooms() {

        FacesContext ctx = FacesContext.getCurrentInstance();
        Application app = ctx.getApplication();
        ELContext ectx = ctx.getELContext();
        ExpressionFactory ef = app.getExpressionFactory();
        ValueExpression ve = ef.createValueExpression(ectx, "#{bookingBackingBean}", BookingBackingBean.class);
        BookingBackingBean db = (BookingBackingBean) ve.getValue(ectx);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hotel_pu");

        List<Booking> myBookings = Database.getBookingController().findEntities();
        
        IRoomJpaCtrl roomCtrl = new RoomJpaCtrl(null, emf);
        
        //Check if the customer booking startDate is the same as 
        //our booking startDate. (if this is the case then it would't be available)
        List<Integer> roomNbrs = new ArrayList<Integer>();
        for (Booking aBooking : myBookings) {
          
            String customerDateBook = db.getFromDate() + " 00:00";
            String bookingStartDate = DateFormat.getInstance().format(aBooking.getStartDate());

            if (bookingStartDate.compareTo(customerDateBook) == 0) {
                roomNbrs.add(aBooking.getRoom().getRoomNb());
            }
        }

         
        freeRooms = roomCtrl.findAvailableRooms(roomNbrs);
    }

    public void setRooms(List<ViewFreeRoomsBackingBean> b) {
        this.freeRooms = b;
    }
}